<template>
  <el-dialog :title="formTitle" :visible.sync="addDialogVisible" width="50%"
             :close-on-click-modal="false" @close="addDialogClosed">
    <!-- 内容主题区 -->
    <el-form style="padding:0 10px" :model="addForm" :rules="addFormRules"
             ref="addFormRef" label-width="100px">

      <el-form-item label="监控项名称" prop="name">
        <el-input v-model="addForm.name" placeholder="请输入监控项名称"></el-input>
      </el-form-item>

      <el-form-item label="主机接口">
        <!-- interfaceid -->

        <el-input v-model="addForm.interfaceInfo" disabled
                  style="width:calc(80% - 5px);margin-right:5px"></el-input>
      </el-form-item>
      <!-- @change="changeTemplate" -->
      <!-- <el-form-item label="选择模板" prop="templateid">
        
        <el-select clearable v-model="addForm.templateid" filterable placeholder="请选择监控项"
                   style="width:calc(80% - 5px);margin-right:5px">
          <el-option v-for="(item, index) in templateList" :key="index"
                     :label="item.name" :value="item.templateid"></el-option>
        </el-select>

      </el-form-item> -->

      <el-form-item label="监控功能" prop="key">
        <!-- @change="changeTemplate" -->
        <el-select clearable v-model="addForm.key" filterable
                   placeholder="请选择监控项"
                   style="width:calc(80% - 5px);margin-right:5px">
          <el-option v-for="(item, index) in keyDatas" :key="index"
                     :label="item.name" :value="item.key"></el-option>
        </el-select>

      </el-form-item>

      <el-row>
        <el-col :span="11">
          <el-form-item label="监控数值单位">
            <el-select clearable v-model="addForm.units"  :disabled="itemKeyDisable"  >
              <el-option :value="item" :label="item"
                         v-for="(item,index) in keyUnitList" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="数值类型">
            <el-select clearable v-model="addForm.valueType"  :disabled="itemKeyDisable" >
              <el-option :value="item.value" :label="item.lable"
                         v-for="(item,index) in valueTypeList" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-form-item label="监听端口" prop="port" v-if="addForm.itemTemplateId == 6">
        <el-input v-model="addForm.port" placeholder="请输入需要监听的端口"></el-input>
      </el-form-item> -->

      <el-form-item label="采集间隔" prop="delay">

        <el-input v-model="addForm.delay" placeholder="请输入采集间隔时间"
                  style="width:calc(80% - 5px);margin-right:5px"></el-input>

        <el-select clearable v-model="addForm.delayUnit" style="width:20%">
          <el-option :value="item.value" :label="item.lable"
                     v-for="(item,index) in unitList" :key="index"></el-option>
        </el-select>

      </el-form-item>

      <el-form-item label="历史记录" prop="history">
        <el-input v-model="addForm.history" placeholder="请输入历史记录时间"
                  style="width:calc(80% - 5px);margin-right:5px"></el-input>
        <el-select clearable v-model="addForm.historyUnit" style="width:20%">
          <el-option :value="item.value" :label="item.lable"
                     v-for="(item,index) in hisUnit" :key="index"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="趋势" prop="trends">
        <el-input v-model="addForm.trends" placeholder="请输入趋势记录时间"
                  style="width:calc(80% - 5px);margin-right:5px"></el-input>
        <el-select clearable v-model="addForm.trendUnit" style="width:20%">
          <el-option :value="item.value" :label="item.lable"
                     v-for="(item,index) in trendUnit" :key="index"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <!-- 底部区 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="addDialogClosed">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script type="text/javascript">
/*
 * @author 宋辉辉
 * @description 监控项创建视图层
 * @api 暂无
 * @since 2021年11月8日18:10:00
 * @update 2021年11月8日18:10:05
 * @modifier 宋辉辉
 * @bug 无
 * @version v1.0.0
 */
import { doAdd, doEdit, getOne, getAllKeys, getItemList, isHaveItem } from
  '@/api/monitor/config/host/item'

import { getList as getTemplateList } from '@/api/monitor/config/template'

export default {
  name: 'itemAdd',
  data () {

    let checkUsername = async (rule, name, callback) => {
      // console.log(rule);
      // console.log(name);
      let ret = await getItemList({
        query: {
          name
        },
        page: {
          current: 1,
          size: 10
        }
      })
      console.log(ret);
      if (ret.code == 20000 && ret.data.total > 0) {
        callback(new Error('名称已存在'))
      }
    }

    let checkItemKey = async (rule, value, callback) => {
      console.log(rule);
      console.log(value);
      console.log(this.hostDetail.hostid);
      let ret = await isHaveItem({
        hostId: this.hostDetail.hostid,
        key: value
      })
      console.log(ret);
      if (ret.code == 20000) {
        callback(new Error('该功能已存在'))
      }
    }

    let checkNumber = (rule, value, callback) => {

      if (parseInt(value) > 0) {
        callback()
      } else {
        callback(new Error('请输大于0的数字'))
      }
    }



    return {

      // 监控项无单位时，为 true
      itemKeyDisable:false,

      hostDetail: null,

      formTitle: '新增监控项',
      addDialogVisible: false,
      addForm: {
        name: "",
        key: "",
        units: '',  // key 值的 单位
        interfaceInfo: '',
        history: "",
        historyUnit: "d",
        trends: "",
        type: 0, // 0 固定值
        valueType: 0,
        trendUnit: "d",
        interfaceid: "",
        hostid: "",
        delayUnit: "m",
        delay: ""
      },
      addFormRules: {

        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          // { validator: checkUsername, trigger: 'blur' },
        ],

        key: [
          { required: true, message: '请选择监控功能', trigger: 'blur' },
          { validator: checkItemKey, trigger: 'change' },
        ],

        templateid: [
          { required: false, message: '请选择监控项模板', trigger: 'change' }
        ],

        // port: [
        //   { required: true, message: '请输入需要监听的端口', trigger: 'blur' }
        // ],
        delay: [
          { required: true, message: '请输入采集间隔时间!', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' },
        ],
        history: [
          { required: true, message: '请输入历史记录时间', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' },
        ],
        trends: [
          { required: true, message: '请输入趋势记录时间', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' },
        ]
      },
      keyDatas: [],
      details: [],

      templateList: [],
      keyUnitList: [],

      unitList: [{
        value: 'm',
        lable: '分钟'
      }, {
        value: 'h',
        lable: '小时'
      }, {
        value: 'd',
        lable: '天'
      }],

      hisUnit: [{
        value: 'h',
        lable: '小时'
      }, {
        value: 'd',
        lable: '天'
      }, {
        value: 'w',
        lable: '天'
      }

      ],

      valueTypeList: [{
        value: 0,
        lable: '数值'
      }, {
        value: 4,
        lable: '字符'
      },{
        value: 3,
        lable: '无'
      },

      ],


      trendUnit: [{
        value: 'd',
        lable: '天'
      }],
    }

  },
  async created () {
    // const { data } = await templateList()
    // this.addForm.hostid = this.$route.params.id
    // this.addForm.interfaceid = this.$route.params.interfaceid
    // this.keyDatas = data;


    console.log("------------------------------------------------");

    // 获得所有键值 
    let ret = await getAllKeys()
    console.log(ret, '789');
    if (ret.code == 20000) {
      this.keyDatas = ret.data



    }

    // 获得 模板
    let res = await getTemplateList({
      query: {
        host: '',
      },
      page: {
        current: 1,
        size: 10000,
      },
    })
    console.log(res);
    if (res.code == 20000) {
      this.templateList = res.data.records
    }



  },

  watch: {

    "addForm.key": {
      // 所选择公司发生改变时
      async handler (newValue, oldValue) {
        console.log(newValue);
        // 根据公司，获得该公司的部门
        if (!newValue) return

        let keyObj = this.keyDatas.find(el => this.addForm.key == el.key)

        console.log(keyObj);
        
        this.keyUnitList = JSON.parse(keyObj.units)
        if (this.keyUnitList && this.keyUnitList.length > 0) {
          this.addForm.units = this.keyUnitList[0] || ''
          console.log(this.addForm.units);
        } else {
          this.addForm.units = ''
        }

        // 根据 KEY 获得 keyid
        this.addForm.keyid = keyObj.keyid


        // 当没有单位时
        if(!keyObj.units){

          this.addForm.valueType = 3
          this.itemKeyDisable = true
        }else{
          this.itemKeyDisable = false
        }


      }
    },

  },


  methods: {
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
      this.$emit('init', '')
      this.addDialogVisible = false
    },


    async open (row, hostDetail) {
      this.hostDetail = hostDetail

      this.addDialogVisible = true

      console.log(this.hostDetail);
      console.log(row)

      // console.log(row,"12131321321321")
      if (!row) {
        this.formTitle = '添加监控项'
        // 清空 addForm
        this.addForm = this.$options.data().addForm

        if (this.$refs['addFormRef']) {
          this.$refs['addFormRef'].resetFields()
        }

      } else {
        this.formTitle = '修改监控项'

        console.log(JSON.stringify(row));

        console.log(JSON.stringify(this.addForm));

        Object.assign(this.addForm, row)
        this.addForm.id = row.itemid;

        this.addForm.delayUnit = this.addForm.delay.substring(this.addForm.delay.length - 1)
        this.addForm.delay = this.addForm.delay.substring(0, this.addForm.delay.length - 1)

        this.addForm.historyUnit = this.addForm.history.substring(this.addForm.history.length - 1)
        this.addForm.history = this.addForm.history.substring(0, this.addForm.history.length - 1)

        // this.addForm.trendUnit = this.addForm.trends.substring(this.addForm.trends.length - 1)
        this.addForm.trendUnit = 'd' // 该单位只有一个，天
        this.addForm.trends = this.addForm.trends.substring(0, this.addForm.trends.length - 1)


        console.log(this.addForm);
      }

      this.addForm.interfaceInfo = `${this.hostDetail.interfaces[0].ip} : ${this.hostDetail.interfaces[0].port}`


    },


    save () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return

        // console.log(this.addForm);

        this.addForm.hostid = this.hostDetail.hostid
        this.addForm.interfaceid = this.hostDetail.interfaces[0].interfaceid
        this.addForm.delay = this.addForm.delay + this.addForm.delayUnit
        this.addForm.history = this.addForm.history + this.addForm.historyUnit
        this.addForm.trends = this.addForm.trends + this.addForm.trendUnit

        console.log(this.addForm);

        let res = null
        if (this.addForm.id) {
          res = await doEdit(this.addForm)
        } else {
          res = await doAdd(this.addForm)

        }
        console.log(res);
        if (res.code == 20000) {
          this.$message({
            type: 'success',
            message: res.message
          })
        }

        this.addDialogVisible = false;
      })
    },
    changeTemplate (e) {
      this.keyDatas.map((item, i) => {
        if (item.key == e) {
          this.addForm.name = item.name; //传值
        }
      });

      /*    let list = this.keyDatas.filter(item => item.id == this.addForm.itemId)
          let {delay,intervalUnit,history,historyUnit,trends,trendUnit} =  list[0]
         this.addForm = Object.assign(this.addForm, {
           delay,
           intervalUnit,
           history,
           historyUnit,
           trends,
           trendUnit
         })*/
    }
  }
}
</script>

<style scoped></style>
